#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include "socket.h"
struct FdInfo
{
    int fd;
    int count; //记录有多少次没有收到心跳包回复的数据
};
pthread_mutex_t mutex;

void* parseRecvMessage(void* arg)
{
    struct FdInfo *info = (struct FdInfo*)arg;
    while(1)
    {
        char* buffer;
        enum Type t;
        recvMessage(info->fd,&buffer,&t);
        if(buffer == NULL)
        {
            continue; 
        }
        else
        {
            if(t == Heart)
            {
                printf("心跳包，%s\n",buffer);
                pthread_mutex_lock(&mutex);
                info->count = 0;//接受到服务器发送过来的心跳包，count重置为0
                pthread_mutex_unlock(&mutex);
            }
            else
            {
                printf("数据包，%s\n",buffer);
            }
            free(buffer); 
        }
    }
    return NULL;
}
// 1.给服务器发送心跳包数据
// 2.心跳包检测，看是否能够收到服务器回复的数据
void* heartBeat(void* arg)
{
    struct FdInfo *info = (struct FdInfo*)arg;
    while(1)   
    {
        pthread_mutex_lock(&mutex);
        info->count++;
        printf("fd = %d,count = %d\n",info->fd,info->count);
        if(info->count > 5)
        {
            printf("客户端与服务器断开连接\n");
            //释放套接字资源
            close(info->fd);
            //退出客户端
            exit(0);
        }
        pthread_mutex_unlock(&mutex);   
        sendMessage(info->fd,"hello",5,Heart);
        sleep(3);
    }
    return NULL;
}
int main()
{
    struct FdInfo info;
    unsigned short port = 8888;
    const char* ip = "127.0.0.1";
    info.fd = initSocket();
    printf("客户端fd ； %d\n",info.fd);
    info.count = 0;
    connectToHost(info.fd,port,ip);

    pthread_mutex_init(&mutex,NULL);

    //创建用于接受数据的子线程
    pthread_t pid;
    pthread_create(&pid,NULL,parseRecvMessage,&info);
    //添加心跳包子线程
    pthread_t pid1;
    pthread_create(&pid1,NULL,heartBeat,&info);
    while(1)
    {
        const char* message = "hello world";
        //发送数据
        sendMessage(info.fd,message,strlen(message),Message);
        sleep(2);
    }
    pthread_join(pid,NULL);
    pthread_join(pid1,NULL); 
    pthread_mutex_destroy(&mutex);
    return 0;
}